package com.dlc.yunguang.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import com.dlc.commonlibrary.ble.RfidHelper;
import com.dlc.commonlibrary.dialog.SureDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.commonlibrary.widget.popup.CommonPopupList;
import com.dlc.yunguang.adapter.LaundryAdapter;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.helper.DBManager;
import com.dlc.yunguang.net.bean.BackBean;
import com.dlc.yunguang.net.bean.HotelRfidBean;
import com.dlc.yunguang.net.bean.OfficeBean;
import com.dlc.yunguang.net.bean.OrderDetailBean;
import com.dlc.yunguang.net.bean.RFIDSpecListBean;
import com.dlc.yunguang.net.exception.ErrorMsgException;
import com.dlc.yunguang.net.protocol.StockProto;
import com.dlc.yunguang.net.protocol.base.HttpProtocol;
import com.dlc.yunguang.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/19 0019.
 */

public class ChuKuActivity extends BaseActivity {

    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.order_number)
    TextView mOrderNumber;
    @BindView(R.id.hotel)
    TextView mHotel;
    @BindView(R.id.pro_name)
    TextView mProName;
    @BindView(R.id.classify)
    TextView mClassify;
    @BindView(R.id.pro_count)
    TextView mProCount;
    @BindView(R.id.check)
    Button mCheck;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_hotel)
    TextView mTvHotel;
    @BindView(R.id.drop_hotel)
    FrameLayout mDropHotel;
    @BindView(R.id.item_hotel)
    CommonItemView mItemHotel;

    private Handler mHandler;
    private LaundryAdapter mLaundryAdapter;

    private ArrayList<String> rfids = new ArrayList<>();
    private String pagesize = "10000";
    private DBManager dbManager = DBManager.getInstance(this);
    private ArrayList<String> saveList = new ArrayList<>();//在数据库中保存的RFID
    List<String> SumList = new ArrayList<>();
    private CommonPopupList mHotelPopup;//酒店
    List<OfficeBean.DataBean> HotelList = new ArrayList<>();
    private String HotelId = null;
    private List<String> officeList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleBar.leftImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.titleText.setText("送洗出库");
        mHandler = new Handler();
        rfids = getIntent().getStringArrayListExtra("rfids");

        // 查询送货单详情
        initRecyclerView();
        getDbData();
        savaDb(rfids);
    }

    /**
     * 获取数据库的数据
     */
    private void getDbData() {
        List<HotelRfidBean> list = dbManager.queryLabelListHotel();
        for (HotelRfidBean bean : list) {
            saveList.add(bean.getRfid());
        }
        if (saveList.size() > 0) {
            LogPlus.e(saveList.toString());
            if (rfids != null) {
                SumList.addAll(rfids);
            }
            SumList.addAll(saveList);
            SumList = RfidHelper.removeDuplicateWithOrder(SumList);
            ToastUtil.show(ChuKuActivity.this, "存在未提交数据");
        } else {
            if (rfids != null) {
                SumList.addAll(rfids);
            }
        }
        mOrderNumber.setText(String.valueOf(SumList.size()));
        queryOrderDetail();
    }

    private void isSaveData() {
        if (rfids.size() > 0) {
            SureDialog sureDialog = new SureDialog(ChuKuActivity.this, "是否确定保存数据");
            sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                @Override
                public void sure() {
                    //Intent intent = new Intent();
                    //intent.putStringArrayListExtra("rfid",rfids);
                    //setResult(RESULT_OK, intent); //intent为A传来的带有Bundle的intent，当然也可以自己定义新的Bundle
                    savaDb(rfids);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 2000);
                }

                @Override
                public void cancle() {
                    finish();
                }
            });
        } else {
            finish();
        }
    }

    private void savaDb(ArrayList<String> list) {
        long timeStamp = System.currentTimeMillis();
        for (String string : list) {
            HotelRfidBean bean = new HotelRfidBean(null, string, timeStamp);
            dbManager.insertHotelLabel(bean);
        }
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_chuku_hotel;
    }

    private void initRecyclerView() {
        mLaundryAdapter = new LaundryAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mLaundryAdapter);
        mHotelPopup = CommonPopupList.newBuilder(getActivity())
            .setWidthEquals(mDropHotel)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    // TODO: 2017/7/20
                    mTvHotel.setText(item);
                    if (HotelList != null) {
                        HotelId = HotelList.get(position).id;
                    }
                }
            })
            .build();
    }

    /**
     * 查询订单详情
     */
    private void queryOrderDetail() {
        String rfid = "";
        for (int i = 0; i < SumList.size(); i++) {
            rfid = rfid + SumList.get(i) + ",";
        }
        if (!TextUtils.isEmpty(rfid)) {
            rfid = rfid.substring(0, rfid.length() - 1);
        } else {
            rfid = "-1";
        }
        mOrderNumber.setText(String.valueOf(SumList.size()));
        StockProto.get()
            .rfid_spec(rfid)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<RFIDSpecListBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showOneToast(e.getMessage());
                }

                @Override
                public void onNext(RFIDSpecListBean dataBean) {
                    mLaundryAdapter.setNewData(dataBean.data);
                    String hotel_id = "";
                    for (RFIDSpecListBean.DataBean bean : dataBean.data){
                        if (!TextUtils.isEmpty(bean.office)) {
                            officeList.add(bean.office);
                            hotel_id = bean.hotel_id;
                        }
                    }
                    officeList = RfidHelper.removeDuplicateWithOrder(officeList);
                    getPopupListData(hotel_id);
                }
            });
    }
    private void getPopupListData(String  hotel_id) {
        StockProto.get().getOffice(hotel_id).
            subscribeOn(Schedulers.io()).
            observeOn(AndroidSchedulers.mainThread()).
            subscribe(new Observer<OfficeBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    LogPlus.e(e.getMessage());
                }

                @Override
                public void onNext(OfficeBean hotelBean) {
                    if (hotelBean != null && hotelBean.data != null) {
                        List<String> datas = new ArrayList<>();
                        //HotelBean.DataBean bean1 = new HotelBean.DataBean();
                        //bean1.setTitle(getString(R.string.choose_all));
                        //HotelList.add(bean1);
                        //for (int i = 0; i < hotelBean.data.size(); i++) {
                        //    HotelList.add(hotelBean.data.get(i));
                        //}

                        Iterator<OfficeBean.DataBean> it = hotelBean.data.iterator();
                        //while(it.hasNext()){
                        //    String str = it.next().title;
                        for (int j = 0;j < hotelBean.data.size();j++) {
                            for (int i = 0; i < officeList.size(); i++) {
                                if (officeList.get(i).equals(hotelBean.data.get(j).title)) {
                                    HotelList.add(hotelBean.data.get(j));
                                }
                            }
                        }
                        // }
                        for (int i = 0;i < HotelList.size();i++){
                            datas.add(HotelList.get(i).title);
                        }

                        mHotelPopup.setData(datas);
                    }
                }
            });
    }

    private void commitData() {
        String rfid = "";
        for (int i = 0; i < SumList.size(); i++) {
            rfid = rfid + SumList.get(i) + ",";
        }
        if (!TextUtils.isEmpty(rfid)) {
            rfid = rfid.substring(0, rfid.length() - 1);
        } else {
            rfid = "-1";
        }
        order_wash_new(rfid,"", "");
        //StockProto.get().order_wash_new(rfid)
        //    .subscribeOn(Schedulers.io())
        //    .observeOn(AndroidSchedulers.mainThread())
        //    .subscribe(new Subscriber<WashBean>() {
        //        @Override
        //        public void onCompleted() {
        //
        //        }
        //
        //        @Override
        //        public void onError(Throwable e) {
        //            showOneToast(e.getMessage());
        //        }
        //
        //        @Override
        //        public void onNext(WashBean dataBean) {
        //            dbManager.deleteLabelAllHotel();
        //            showOneToast(dataBean.msg);
        //            getDetailData(dataBean.data.order_id+"");
        //        }
        //    });
    }

    private void order_wash_new(final String rfid,String office, String confirm) {
        StockProto.get().order_wash_new(rfid,office, confirm, new HttpProtocol.Callback<BackBean>() {
            @Override
            public void onSuccess(BackBean dataBean) {
                dbManager.deleteLabelAll();
                showOneToast(dataBean.msg);
                getDetailData(dataBean.data.order_id + "");
            }

            @Override
            public void onFailed(int code, ErrorMsgException e) {
                showOneToast(e.getMessage());
                if (code == -101) {
                    SureDialog sureDialog =
                        new SureDialog(ChuKuActivity.this, "提示有其他科室布草，是否确定生成送洗单，选“确定”，可以生成送洗单。");
                    sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                        @Override
                        public void sure() {
                            order_wash_new(rfid,HotelId, "1");
                        }

                        @Override
                        public void cancle() {
                            finish();
                        }
                    });
                }
            }
        });
    }

    private void getDetailData(String id) {
        StockProto.get()
            .getOrderDetail("order_wash_detail", id, new HttpProtocol.Callback<OrderDetailBean>() {
                @Override
                public void onSuccess(OrderDetailBean orderDetailBean) {
                    dismissLoadingDialog();
                    Toast.makeText(getActivity(), orderDetailBean.msg, Toast.LENGTH_SHORT).show();
                    finish();
                    Intent intent = new Intent(getActivity(), OrderDetailActivity1.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("detailData", orderDetailBean);
                    intent.putExtras(bundle);
                    intent.putExtra("type", 0);
                    startActivity(intent);
                }

                @Override
                public void onFailed(int code, ErrorMsgException e) {
                    Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    dismissLoadingDialog();
                }
            });
    }

    @OnClick({ R.id.check,R.id.drop_hotel })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check:
                if (TextUtils.isEmpty(HotelId)){
                    showOneToast("请选择科室");
                    return;
                }
                SureDialog sureDialog = new SureDialog(ChuKuActivity.this, "全部读取完成，确认提交");
                sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                    @Override
                    public void sure() {
                        commitData();
                    }

                    @Override
                    public void cancle() {

                    }
                });
                break;
            case R.id.drop_hotel:
                mHotelPopup.showAsDropDown(view);
                break;
        }
    }
}



